<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import {
  getCartList,
  removeFromCart,
  addToCart,
  deleteCartItem,
  clearCart,
  updateCartQuantity,
} from "@/api/cart";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus, Minus, Delete } from "@element-plus/icons-vue";
import request from "@/utils/request";
import type { CartItem } from "@/types/cart";

const cartList = ref<CartItem[]>([]);
const loading = ref(false);
const selectAll = ref(false);
const tableRef = ref();

// 获取购物车列表
const fetchCartList = async () => {
  loading.value = true;
  try {
    const res = await getCartList();
    if (res.success) {
      cartList.value = res.data;
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("获取购物车列表失败");
  } finally {
    loading.value = false;
  }
};

// 删除购物车商品
const handleDelete = async (shoppingCartId: number) => {
  try {
    await ElMessageBox.confirm("确定要从购物车中删除该商品吗？", "提示", {
      type: "warning",
    });

    const res = await deleteCartItem({
      id: shoppingCartId,
    });

    if (res.success) {
      ElMessage.success("删除成功");
      await fetchCartList();
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("删除失败");
  }
};

// 修改商品数量
const handleQuantityChange = async (item: CartItem, changeAmount: number) => {
  try {
    const res = await addToCart(item.id, changeAmount);
    if (res.success) {
      await fetchCartList();
      ElMessage.success("数量更新成功");
    } else {
      ElMessage.error(res.message || "更新数量失败");
    }
  } catch (error) {
    console.error("更新数量失败:", error);
    ElMessage.error("更新数量失败");
  }
};

// 计算总价
const totalPrice = computed(() => {
  const selectedRows = tableRef.value?.getSelectionRows() || [];
  return selectedRows.reduce(
    (total: number, item: CartItem) => total + item.price * item.quantity,
    0
  );
});

// 获取商品类型文本
const getProductTypeText = (type: number) => {
  const typeMap = {
    1: "果蔬",
    2: "畜产",
    3: "水产",
  };
  return typeMap[type as keyof typeof typeMap] || "未知";
};

// 清空购物车
const handleClearCart = async () => {
  try {
    await ElMessageBox.confirm("确定要清空购物车吗？此操作不可恢复！", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const res = await clearCart();
    if (res.success) {
      ElMessage.success("购物车已清空");
      await fetchCartList();
    }
  } catch (error) {
    console.error(error);
    ElMessage.error("清空购物车失败");
  }
};

// 计算选中的商品数量
const selectedCount = computed(() => {
  return tableRef.value?.getSelectionRows().length || 0;
});

// 计算是否有选中的商品
const hasSelected = computed(() => selectedCount.value > 0);

// 全选/取消全选
const handleSelectAll = (val: boolean) => {
  cartList.value.forEach((row) => {
    tableRef.value?.toggleRowSelection(row, val);
  });
};

// 去结算
const handleCheckout = async () => {
  const selectedRows = tableRef.value?.getSelectionRows();
  if (!selectedRows?.length) {
    ElMessage.warning("请选择要购买的商品");
    return;
  }

  try {
    // 计算选中商品的总金额
    const totalAmount = selectedRows
      .reduce(
        (total: number, item: CartItem) => total + item.price * item.quantity,
        0
      )
      .toFixed(2);

    // 获取选中商品的购物车ID数组
    const shoppingCartIds = selectedRows.map(
      (item: CartItem) => item.shoppingCartId
    );

    const res = await request({
      url: "/productOrder/add",
      method: "post",
      data: {
        totalAmount,
        shoppingCartIds,
      },
    });

    if (res.success) {
      ElMessage.success("下单成功");
      // 刷新购物车列表
      await fetchCartList();
      // TODO: 可以跳转到订单列表页面
    } else {
      ElMessage.error("下单失败");
    }
  } catch (error) {
    ElMessage.error("下单失败");
  }
};

// 添加一个用于格式化日期的函数
const formatDate = (dateString: string) => {
  if (!dateString) return "暂无数据";
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
    2,
    "0"
  )}-${String(date.getDate()).padStart(2, "0")}`;
};

// 获取商品类型对应的 tag 类型
const getProductTypeTag = (type: number) => {
  const typeMap = {
    1: "success",
    2: "warning",
    3: "info",
  };
  return typeMap[type as keyof typeof typeMap] || "info";
};

const calculateTotal = computed(() => {
  return cartList.value
    .filter((item: CartItem) => item.selected)
    .reduce(
      (total: number, item: CartItem) => total + item.price * item.quantity,
      0
    );
});

const calculateSelectedCount = computed(() => {
  return cartList.value.filter((item: CartItem) => item.selected).length;
});

const handleRemove = async (item: CartItem) => {
  try {
    await removeFromCart(item.shoppingCartId);
    await fetchCartList();
    ElMessage.success("商品已移除");
  } catch (error) {
    console.error("移除商品失败:", error);
    ElMessage.error("移除商品失败");
  }
};

onMounted(() => {
  fetchCartList();
});
</script>

<template>
  <div class="cart-container">
    <el-card class="cart-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <h2 class="title">我的购物车</h2>
            <span class="subtitle">共 {{ cartList.length }} 件商品</span>
          </div>
          <el-button
            type="danger"
            link
            @click="handleClearCart"
            class="clear-btn"
          >
            <el-icon><Delete /></el-icon>
            清空购物车
          </el-button>
        </div>
      </template>

      <el-table
        :data="cartList"
        ref="tableRef"
        :header-cell-style="{
          background: '#f8f9fa',
          color: '#606266',
          fontWeight: 500,
        }"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column label="商品">
          <template #default="{ row }">
            <div class="product-info">
              <el-image
                :src="row.avatar"
                fit="cover"
                class="product-image"
                :preview-src-list="[row.avatar]"
              />
              <div class="product-details">
                <div class="product-name">{{ row.name }}</div>
                <div class="product-meta">
                  <el-tag
                    size="small"
                    :type="getProductTypeTag(row.productType)"
                    effect="light"
                  >
                    {{ getProductTypeText(row.productType) }}
                  </el-tag>
                  <span class="expiration-date"
                    >有效期至：{{ formatDate(row.expirationDate) }}</span
                  >
                </div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="price" label="单价" width="120">
          <template #default="{ row }">
            <span class="price">¥{{ row.price.toFixed(2) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="数量" width="150">
          <template #default="{ row }">
            <div class="quantity-control">
              <el-button
                :icon="Minus"
                class="quantity-btn"
                :disabled="row.quantity <= 1"
                @click="handleQuantityChange(row, -1)"
              />
              <span class="quantity">{{ row.quantity }}</span>
              <el-button
                :icon="Plus"
                class="quantity-btn"
                @click="handleQuantityChange(row, 1)"
              />
            </div>
          </template>
        </el-table-column>

        <el-table-column label="小计" width="120">
          <template #default="{ row }">
            <span class="subtotal"
              >¥{{ (row.price * row.quantity).toFixed(2) }}</span
            >
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button
              type="danger"
              link
              class="delete-btn"
              @click="handleDelete(row.shoppingCartId)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="cart-footer">
        <div class="left">
          <el-checkbox
            v-model="selectAll"
            @change="handleSelectAll"
            class="select-all"
          >
            全选
          </el-checkbox>
        </div>
        <div class="right">
          <span class="total-info">
            已选商品 <span class="count">{{ selectedCount }}</span> 件
          </span>
          <span class="total-price">
            合计：<span class="price">¥{{ totalPrice.toFixed(2) }}</span>
          </span>
          <el-button
            type="primary"
            size="large"
            :disabled="!hasSelected"
            @click="handleCheckout"
            class="checkout-btn"
          >
            去结算
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.cart-container {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.cart-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

  :deep(.el-card__header) {
    padding: 20px 24px;
    border-bottom: 1px solid #ebeef5;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-left {
    display: flex;
    align-items: center;
    gap: 12px;

    .title {
      font-size: 20px;
      font-weight: 600;
      color: #2c3e50;
      margin: 0;
    }

    .subtitle {
      color: #909399;
      font-size: 14px;
    }
  }

  .clear-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
  }
}

.product-info {
  display: flex;
  gap: 16px;
  align-items: center;
  padding: 8px 0;

  .product-image {
    width: 80px;
    height: 80px;
    border-radius: 8px;
    object-fit: cover;
    transition: transform 0.3s ease;

    &:hover {
      transform: scale(1.05);
    }
  }

  .product-details {
    flex: 1;

    .product-name {
      font-size: 14px;
      color: #2c3e50;
      margin-bottom: 8px;
      font-weight: 500;
    }

    .product-meta {
      display: flex;
      align-items: center;
      gap: 12px;

      .expiration-date {
        color: #909399;
        font-size: 12px;
      }
    }
  }
}

.quantity-control {
  display: flex;
  align-items: center;
  gap: 8px;

  .quantity-btn {
    padding: 6px;
    border-radius: 4px;

    &:hover:not(:disabled) {
      background-color: #ecf5ff;
      color: #409eff;
    }
  }

  .quantity {
    min-width: 36px;
    text-align: center;
    font-size: 14px;
    color: #606266;
  }
}

.price,
.subtotal {
  color: #f56c6c;
  font-weight: 500;
  font-size: 15px;
}

.delete-btn {
  display: flex;
  align-items: center;
  gap: 4px;

  &:hover {
    opacity: 0.8;
  }
}

.cart-footer {
  margin-top: 24px;
  padding: 20px 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

  .select-all {
    font-size: 14px;
  }

  .right {
    display: flex;
    align-items: center;
    gap: 24px;

    .total-info {
      font-size: 14px;
      color: #606266;

      .count {
        color: #f56c6c;
        font-weight: 600;
      }
    }

    .total-price {
      font-size: 14px;
      color: #606266;

      .price {
        color: #f56c6c;
        font-size: 24px;
        font-weight: 600;
        margin-left: 4px;
      }
    }

    .checkout-btn {
      min-width: 120px;
      border-radius: 8px;
      font-weight: 500;
      transition: all 0.3s ease;

      &:not(:disabled):hover {
        transform: translateY(-1px);
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
      }
    }
  }
}

// 添加一些动画效果
.el-table {
  .el-table__row {
    transition: all 0.3s ease;

    &:hover {
      background-color: #f5f7fa;
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    }
  }
}
</style> 